package com.weshare.service;

import com.weshare.model.FileCustom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FileService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询未备份的文件
     *
     * @param fileType
     * @param count
     * @return
     */
    public List<FileCustom> fetchUnBackupFiles(String fileType, Integer count) {

        String sql = "select * from t_file t where t.type = ? and t.backedUp = 0 order by id limit 0,?";
        List<FileCustom> query = jdbcTemplate.query(sql, new Object[]{fileType, count}, new BeanPropertyRowMapper<>(FileCustom.class));

        return query;
    }

    /**
     * 备份文件
     *
     * @param files
     */
    public void backupFiles(List<FileCustom> files) {
        for (FileCustom fileCustom : files) {

            String sql = "update t_file set backedUp = 1 where id = ?";
            jdbcTemplate.update(sql, new Object[]{fileCustom.getId()});
            System.out.println(String.format("线程 %d | 已备份文件：%s  文件类型:%s",
                    Thread.currentThread().getName(),
                    fileCustom.getName(),
                    fileCustom.getType()));
        }
    }
}
